﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Helpers;
using System.Web.Http;
using System.Web.Http.Controllers;
using Wechat.API.Models;
using Wechat.Util.Auth;
using Wechat.Util.Date;
using Wechat.Util.ParmsConfig;
using Wechat.Util.Request;
using Wechat.Util.ReturnMessage;
using Wechat.Util.StateCode;

namespace Wechat.API.Filter
{
    /// <summary>
    /// 授权过滤器
    /// </summary>
    public class OnAuthorizeAttribute : AuthorizeAttribute
    {
        /// <summary>
        /// 授权  
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            ResultMessage resultMsg = new ResultMessage();
            resultMsg.Status = false;
            resultMsg.Code = (int)EnumApiStateCode.AuthorizeFailed;

            string authStr = string.Empty;//定义授权变量
            try
            {
                authStr = actionContext.Request.Headers.GetValues("Authorization").FirstOrDefault();
            }
            catch { }

            if (!string.IsNullOrWhiteSpace(authStr))
            {
                Dictionary<string, string> parms = new Dictionary<string, string>();
                foreach (string p in authStr.Split(','))
                {
                    string[] parm = p.Split('=');
                    parms.Add(parm[0], parm[1]);
                }

                var dateTime = DateTimeUtil.ConvertTimeStamp2DateTime(Convert.ToInt64(parms["timestamp"]));//这里解析时间戳
                TimeSpan ts = DateTime.Now - dateTime;//获取到的timespan是4分钟  还剩4分钟过期

                if (ts.TotalMinutes > ParmsConfigUtil.AuthorizeExpiredMin)//这个授权过滤时间是5分钟
                {
                    resultMsg.Code = (int)EnumApiStateCode.AuthorizeExpired;
                    resultMsg.Message = "授权失败，授权已过期！";
                }
                else
                {
                    #region 此处写自己逻辑，做登陆判断，返回用户信息
                    //第一步：根据用户名获取用户信息
                    //第二部：将用户输入的密码进行加密
                    //第三部：将加密后的字符串和密码比较是否相等
                    //相等则继续
                    OperaterInfo operInfo = new OperaterInfo() { Pwd= "gOWWV2PClQF1m9dn7lO7fQ==" };//用户名密码查询操作

                    if (operInfo != null)
                    {
                        string join_str = UserAuth.GenJoinStr(parms["timestamp"], parms["nonce"], parms["key"]);//将读取回来的token的除了密码参数，剩下的匹配
                        //将timestamp、nonce、API_KEY 这三个字符串进行升序排列（依据字符串首位字符的ASCII码)，并join成一个字符串
                        string signature = UserAuth.GenEncryptString(join_str, operInfo.Pwd);//对密码和签名进行加密

                        if (!signature.Equals(parms["signature"]))//如果签名不一致，则授权失败
                        {
                            resultMsg.Code = (int)EnumApiStateCode.ParameterMissing;
                            resultMsg.Message = "授权失败，签名不匹配！";
                        }
                        else
                        {
                            #region 此处可以根据操作员信息，获取权限列表，即可判断是否有当前请求控制器的权限！
                            // //如要模仿，请ctrl  k  u  撤销注释
                            //AuthOptRequest authOptRequest = new AuthOptRequest();
                            ////此处可以根据操作员信息，获取权限列表，即可判断是否有当前请求控制器的权限！
                            ////根据用户信息进行权限查询判断是否有权限
                            //AuthResult result =new AuthOperater().AuthOperaterIsLicit(authOptRequest);

                            ////未登录、重新登录、Cookie解密出错
                            //if (result.AuthStatus == EnumAuthStatus.NoLogin || result.AuthStatus == EnumAuthStatus.AgainLogin || result.AuthStatus == EnumAuthStatus.DecryptError)
                            //{
                            //    resultMsg.Message = "未登录、重新登录、Cookie解密出错！";
                            //}
                            ////认证用户没有权限
                            //else if (result.AuthStatus == EnumAuthStatus.NoPermission)
                            //{
                            //    resultMsg.Message = "认证用户没有权限！";
                            //}
                            #endregion
                        }
                    }
                    else
                    {
                        resultMsg.Message = "授权失败，登录名用户不存在！";
                    }
                    #endregion

                }
            }
            else
            {
                resultMsg.Message = "授权失败，授权参数不为空！";
            }
            if (!string.IsNullOrWhiteSpace(resultMsg.Message))
            {
                var response = actionContext.Response = actionContext.Response ?? new HttpResponseMessage();
                response.StatusCode = HttpStatusCode.Forbidden;

                response.Content =
                                new StringContent(
                                    Json.Encode(new
                                    {
                                        status = resultMsg.Status,
                                        code = resultMsg.Code,
                                        message = resultMsg.Message
                                    }), Encoding.UTF8, "application/json");
            }
        }
    }
}